package com.mstanford.movie.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mstanford.movie.dao.MovieDao;

public class AddTicketServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String json = "{\"result\":true}";
		
		String ticketPlay = request.getParameter("ticketPlay");
		String ticketMember = request.getParameter("ticketMember");
		String ticketSeat = request.getParameter("ticketSeat");
		String ticketPrice = request.getParameter("ticketPrice");
		String ticketFlag = request.getParameter("ticketFlag");
		
		float totalPrice = ticketSeat.split(",").length * Float.parseFloat(ticketPrice);

		Map<String, String> map = new HashMap<String, String>();
		map.put("playId", ticketPlay);
		map.put("memberId", ticketMember);
		map.put("ticketSeat", ticketSeat);
		map.put("ticketPrice", ticketPrice);
		map.put("ticketFlag", ticketFlag);
		
		MovieDao dao = new MovieDao();
		
		dao.queryMemberMoneyByMemberId(map);
		float memberMoney = Float.parseFloat(map.get("memberMoney"));
		float money = memberMoney - totalPrice;
		
		if(money < 0) {
			json = "{\"result\":false}";
		} else {
			map.put("memberMoney", money + "");
			
			dao.addTicket(map);
			dao.updateMemberMoneyByMemberId(map);
		}
		
		// 返回Json格式信息
		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.print(json);
		out.flush();
		out.close();
	}
}